package com.hsnn.medstgmini.base.dict.controller;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hsnn.medstgmini.Constants;
import com.hsnn.medstgmini.base.dict.model.DicDrugmaterial;
import com.hsnn.medstgmini.base.dict.service.DicDrugmaterialManager;
import com.hsnn.medstgmini.sys.model.SysUser;
import com.hsnn.medstgmini.util.Pagination;

/**
 *  基础库 数据字典 材质字典 控制层
 * @author hssdzxssh
 *
 */
@Controller
@RequestMapping("/dicDrugmaterial")
public class DicDrugmaterialController {
	
	private static final Logger log = Logger.getLogger(DicDrugmaterialController.class);
	
	@Autowired
	private DicDrugmaterialManager dicDrugmaterialManager;

	
	@Autowired
	private HttpServletRequest request;
	/**
	 *  基础库 数据字典 材质字典 增加
	 * @param request
	 * @param response
	 */
	@RequestMapping(value={"/add","/edit"},method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public Pagination dicDrugmaterialAdd(HttpServletRequest request,HttpServletResponse response) {
		printParams();
		Pagination page=new Pagination();
		SysUser user = (SysUser)request.getSession().getAttribute(Constants.USERINFO);
		DicDrugmaterial dicDrugmaterial = new DicDrugmaterial();
		Date date = new Date();
		SimpleDateFormat fomat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String strDate = fomat.format(date);
		Timestamp ts = new Timestamp(System.currentTimeMillis());  
        String tsStr =strDate;  
        String materialCode = request.getParameter("materialCode").trim();//材质编码
        String materialName = request.getParameter("materialName").trim();//材质
        String materialId = request.getParameter("materialId");//材质id
        String status =request.getParameter("status");//状态
        short number = (short) 1;
        try {  
            ts = Timestamp.valueOf(tsStr);  
            if(null != materialId && !"".equals(materialId)){
            	List<DicDrugmaterial> list = dicDrugmaterialManager.queryDicDrugmaterialById(materialId);
            	DicDrugmaterial data = list.get(0);
            	if(materialCode.equals(data.getMaterialCode())&&materialName.equals(data.getMaterialName())){
            		page.setSuccess(false);
            		page.setMsg("数据未作任何修改，不能保存!");
            		return page;
            	}
            	dicDrugmaterial.setMaterialId(materialId);
            }
            if(null != status && !"".equals(status)){
            	dicDrugmaterial.setStatus(Integer.parseInt(status));
           // 	dicDrugmaterial.setStatus((short) Integer.parseInt(status));
            }else{
            	dicDrugmaterial.setStatus(1);
            	//dicDrugmaterial.setStatus((short) 1);
            }
            dicDrugmaterial.setSortId(number);
            dicDrugmaterial.setUpdDatetime(ts);
            dicDrugmaterial.setMaterialCode(materialCode);
            dicDrugmaterial.setMaterialName(materialName);
            dicDrugmaterial.setUpdUser(user.getId());
            page.setForm(dicDrugmaterial);
	            if(StringUtils.isNotBlank(materialCode)){
	            	List<DicDrugmaterial> list=dicDrugmaterialManager.getMaterialBy("materialCode",materialCode);
	            	 if(list.size()>0){
	            		 if(!list.get(0).getMaterialId().equals(materialId)){
		            		 page.setMsg("材质编码已存在!");
		            		 page.setSuccess(false);
		            		 return page;
	            		 }
	                 }
	            }else{
	            	page.setMsg("请输入材质编码!");
	            	page.setSuccess(false);
	            	return page;
	            }
	            if(StringUtils.isNotBlank(materialName)){
	            	List<DicDrugmaterial> list=dicDrugmaterialManager.getMaterialBy("materialName",materialName);
	            	 if(list.size()>0){
	            		 if(!list.get(0).getMaterialId().equals(materialId)){
		            		 page.setMsg("材质名称已存在!");
		            		 page.setSuccess(false);
		            		 return page;
	            		 }
	                 }
	            }else{
	            	page.setMsg("请输入材质名称!");
	            	page.setSuccess(false);
	            	return page;
	            }
    		dicDrugmaterialManager.addAndEdit(page) ;
    		page.setMsg("保存成功!");
    		page.setSuccess(true);
        } catch (Exception e) {  
            e.printStackTrace(); 
            page.setMsg("保存失败!");
            page.setSuccess(false);
        }
		return page; 
	}
	
	/**
	 *  基础库 数据字典 材质字典 查询所有数据
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	@RequestMapping(value="/dicDrugmaterialListJsp",method={RequestMethod.GET,RequestMethod.POST})
	public String  dicDrugmaterialListJsp(HttpServletRequest request,HttpServletResponse response) throws IOException {
		return "/base/dict/drugMaterialList";
	}
	
	/**
	 * 基础库 数据字典 材质字典 查询及条件查询
	 * 
	 * 用来封装json
	 * @param request
	 * @param result
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping("/dicDrugmaterialList")
	@ResponseBody
	public Pagination getDicDrugspecList(HttpServletRequest request){
		printParams();
		Pagination page =new Pagination(request);
		try{
		String materialCode = request.getParameter("materialCode");
		String materialName = request.getParameter("materialName");
		String status = request.getParameter("status");
		if(StringUtils.isNotBlank(materialCode)){
			page.getConditions().put("materialCode", materialCode.trim());
		}
		if(StringUtils.isNotBlank(materialName)){
			page.getConditions().put("materialName", materialName.trim());
		}
		if(StringUtils.isNotBlank(status)){
			page.getConditions().put("status", status.trim());
		}
		page = dicDrugmaterialManager.queryDicDrugmaterialList(page);
		} catch (Exception e) {
			e.printStackTrace();
		} catch(Error error) {
			error.printStackTrace();
		}
		return page;
	}

	
	
	/**
	 * 
	 *@category 批量启用停用
	 *@author wangbing
	 *@date 2015年6月9日
	 *Pagination
	 */
	@RequestMapping(value={"/enable","/disable"})
	@ResponseBody
	public Pagination batchChangeStatus(String array) {
		printParams();
		Pagination page = new Pagination();
		int sum = 0;
		SysUser user = (SysUser) request.getSession().getAttribute(Constants.USERINFO);
		try {
			if (array != null && !"".equals(array)) {
				Gson gson = new Gson();
				Type type = new TypeToken<List<DicDrugmaterial>>() {
				}.getType();
				List<DicDrugmaterial> list = gson.fromJson(array, type);
				if (list != null && list.size()>0) {
					for (DicDrugmaterial ddt : list) {
						ddt.setUpdUser(user.getId());
						int count = dicDrugmaterialManager.changeStatus(ddt);
						sum += count;
					}
					page.getConditions().put("sum", sum+"");
					page.setSuccess(true);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			page.setSuccess(false);
		}
		return page;
	}
	
	/**
	 * 
	 *@category 获取参数打印
	 *@author wangbing
	 *@date 2015年6月9日
	 *Pagination
	 */
	@SuppressWarnings("rawtypes")
	public void printParams(){
		Enumeration paramNames = request.getParameterNames();
		try {
			while (paramNames.hasMoreElements()) {
				String paramName = (String) paramNames.nextElement();
				String paramValue = request.getParameter(paramName);
				log.info(paramName+":"+paramValue);
			}
		} catch (Exception e) {
			log.error("",e);
		}
	}
	
	/**
	 * 
	 *@category 导出excel
	 *@author wangbing
	 *@date 2015年6月9日
	 *Pagination
	 */
	@RequestMapping("exportExcel")
	@ResponseBody
	public Pagination exportExcel(HttpServletResponse response,String fileName){
		printParams();
		Pagination page = new Pagination();
		String materialCode = request.getParameter("materialCode");
		String materialName = request.getParameter("materialName");
		String status = request.getParameter("status");
		if(StringUtils.isNotBlank(materialCode)){
			page.getConditions().put("materialCode", materialCode.trim());
		}
		if(StringUtils.isNotBlank(materialName)){
			page.getConditions().put("materialName", materialName.trim());
		}
		if(StringUtils.isNotBlank(status)){
			page.getConditions().put("status", status.trim());
		}
		try {
			response.addHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes("GB2312"),"iso8859-1")); 
			OutputStream os= new BufferedOutputStream(response.getOutputStream());  
			 response.setContentType("application/vnd.ms-excel;charset=utf-8");  
			dicDrugmaterialManager.exportExcel(page,os);
		} catch (Exception e) {
			page.setSuccess(false);
			e.printStackTrace();
		}
		return page;
	}
}
